package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.domain.ChatMessageEntity;
import com.mapper.ChatMessageMapper;
import com.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 聊天室信息表 服务实现类
 * </p>
 *
 * @author sly
 * @since 2023-12-30
 */
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessageEntity> implements ChatMessageService {

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    /**
     * 同步添加聊天发言入数据库
     */
    @Override
    public void addMessage(ChatMessageEntity chatMessageEntity) {
        chatMessageMapper.insert(chatMessageEntity);
    }

    /**
     * 异步添加聊天发言入数据库
     */
    @Async
    @Override
    public void asyncAddMessage(ChatMessageEntity chatMessageEntity) {
        chatMessageMapper.insert(chatMessageEntity);
    }

    /**
     * 查询指定时间开始的全部聊天发言
     */
    @Override
    public List<ChatMessageEntity> getMessage(Long chatId, Date date) {
        LambdaQueryWrapper<ChatMessageEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (date != null) {
            queryWrapper.lt(ChatMessageEntity::getCreateTime, date);
        }
        queryWrapper
                .eq(ChatMessageEntity::getChatId, chatId)
                .orderByDesc(ChatMessageEntity::getCreateTime);
        List<ChatMessageEntity> messageEntityList = chatMessageMapper.selectList(queryWrapper);
        return messageEntityList;
    }

    /**
     * 查询指定时间开始的近10条聊天发言
     */
    @Override
    public List<ChatMessageEntity> getMessageTen(Long chatId, Date date) {
        LambdaQueryWrapper<ChatMessageEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (date != null) {
            queryWrapper.lt(ChatMessageEntity::getCreateTime, date);
        }
        queryWrapper
                .eq(ChatMessageEntity::getChatId, chatId)
                .orderByDesc(ChatMessageEntity::getCreateTime)
                .last("limit 10");
        List<ChatMessageEntity> messageEntityList = chatMessageMapper.selectList(queryWrapper);
        return messageEntityList;
    }

}
